package com.shujia.four;

import org.junit.Test;

public class StringTest {

    public static void main(String[] args) {
        /*
        获取一个字符串在另一个字符串中出现的次数。
	    比如：获取“ ab”在 “abkkcadkabkebfkabkskab” 中出现的次数
         */
        String str = "zabkkcadkabkebfkabkskab";
        String sub = "ab";

        int count = 0;
        while (true) {
            int index = str.indexOf(sub);
            if (index == -1) {
                break;
            }
            count++;
            str = str.substring(index + sub.length());
        }
        System.out.println(count);
    }

    @Test
    public void reverseTest() {
        String target = "abcdefg";
        String subStr = "cdef";
        String result = reverse1(target, subStr);
        System.out.println(result);

    }


    public String reverse1(String target, String subStr) {
        // 将一个字符串进行反转。将字符串中指定部分进行反转。比如“abcdefg”反转为”abfedcg”, cdef
        int index = target.indexOf(subStr);
        String start = target.substring(0, index);
        String end = target.substring(index + subStr.length());
        System.out.println(start);
        System.out.println(end);


        return start
                .concat(new StringBuffer(subStr).reverse().toString())
                .concat(end);
    }

    public String reverse(String target, String subStr) {
        // 将一个字符串进行反转。将字符串中指定部分进行反转。比如“abcdefg”反转为”abfedcg”, cdef
        int index = target.indexOf(subStr);
        String start = target.substring(0, index);
        String end = target.substring(index + subStr.length());
        System.out.println(start);
        System.out.println(end);

        char[] arr = subStr.toCharArray();
        for (int i = 0; i < arr.length / 2; i++) {
            char temp = arr[i];
            arr[i] = arr[arr.length - 1 - i];
            arr[arr.length - 1 - i] = temp;
        }

        return start.concat(new String(arr)).concat(end);
        // return start + new String(arr) + end;
    }


    @Test
    public void trimTest() {
        String str = "    ab   c    ";
        System.out.println(trim(str));
    }

    // 模拟一个trim方法，去除字符串两端的空格。
    public String trim(String target) {
//        return target.trim();
        //     abc
        // 需要获取a和c的下标, 再截取
        int startIndex = 0;
        int endIndex = 0;
        char[] arr = target.toCharArray();
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] != ' ') {
                startIndex = i;
                break;
            }
        }

        for (int i = arr.length - 1; i >= 0; i--) {
            if (arr[i] != ' ') {
                endIndex = i;
                break;
            }
        }
        return target.substring(startIndex, endIndex + 1);
    }
}
